package com.example.demo.exception;

import org.apache.commons.logging.LogFactory;
import org.apache.logging.slf4j.Log4jLoggerFactory;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
import org.jboss.logging.Logger;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.alibaba.druid.support.logging.Log;

import org.apache.ibatis.logging.log4j2.*;

@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
	Logger logger = Logger.getLogger(this.getClass());

    /**
     * 400 - Bad Request
     */
    @ResponseStatus()
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("参数解析失败", e);
        return new Response().failure("could_not_read_json");
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus()
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error("不支持当前请求方法", e);
        return new Response().failure("request_method_not_supported");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus()
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Response handleHttpMediaTypeNotSupportedException(Exception e) {
        logger.error("不支持当前媒体类型", e);
        return new Response().failure("content_type_not_supported");
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus()
    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
        logger.error("服务运行异常", e);
        System.err.println(e.getMessage());
        System.err.println(e.getLocalizedMessage());
        System.err.println(e.getCause());
        System.err.println(e.getClass());
        System.err.println(e.getSuppressed());
        e.printStackTrace();
        System.err.println("");
        return new Response().failure(e.getMessage());
    }
}